package com.xyy.kingdeejdy.service.erp.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.smecloud.apigw.client.ApigwClient;
import com.smecloud.apigw.constant.HttpMethod;
import com.smecloud.apigw.model.ApiRequest;
import com.smecloud.apigw.model.ApiResult;
import com.xyy.kingdeejdy.helper.JdApi;
import com.xyy.kingdeejdy.param.JdCustomerFilter;
import com.xyy.kingdeejdy.param.JdOrderInfoFilter;
import com.xyy.kingdeejdy.param.JdProductFilter;
import com.xyy.kingdeejdy.param.JdStockFilter;
import com.xyy.kingdeejdy.pojo.erp.JdOrderPushInfo;
import com.xyy.kingdeejdy.pojo.erp.customer.JdCustomerPo;
import com.xyy.kingdeejdy.pojo.erp.help.JdyResult;
import com.xyy.kingdeejdy.pojo.erp.order.JdOrderSave;
import com.xyy.kingdeejdy.pojo.erp.order.OrderDetailSku;
import com.xyy.kingdeejdy.pojo.erp.product.JdProductInfoDto;
import com.xyy.kingdeejdy.pojo.erp.product.JdProductStockDto;
import com.xyy.kingdeejdy.pojo.erp.product.Stcok;
import com.xyy.kingdeejdy.pojo.pop.SellerOrderDeliverDetailDto;
import com.xyy.kingdeejdy.service.erp.JdToPopService;
import com.xyy.kingdeejdy.utils.DateUtils;
import com.xyy.kingdeejdy.utils.TokenCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

import static com.xyy.kingdeejdy.utils.DateUtils.SHORT_DATE_FORMAT_STR;

@Slf4j
@Service
public class JdToPopServiceImpl implements JdToPopService {
    private String JdConfig = "api.kingdee.com";

    @Override
    public JdyResult productInfoList(JdProductFilter jdProductFilter) {
        ApiRequest request = new ApiRequest(HttpMethod.POST_BODY, JdConfig, "/jdyscm/product/list");
        Map<String, String> map = new HashMap<>();
        map.put("access_token", TokenCache.getToken());
        map.put("dbId", "796392012921816");
        request.setQuerys(map);
        if (jdProductFilter != null) {
            //log.info("查询参数: {}", JSON.toJSONString(jdProductFilter));
            Map<String, String> map1 = new HashMap<>();
            map1.put("filter", JSON.toJSONString(jdProductFilter));
            byte[] jsonBytes = JSON.toJSONBytes(map1);
            request.setBodyJson(jsonBytes);
        }
        ApiResult send = ApigwClient.getInstance().send(request);
        if (send == null || send.getHttpCode() != 200) {
            log.warn("未获取到金蝶商品信息!!! jsonData: {} param:{}", JSON.toJSONString(send), JSON.toJSONString(jdProductFilter));
            return new JdyResult();
        }
        JdyResult jdyResult = JSON.parseObject(send.getBody(), JdyResult.class);
        if (jdyResult.getCode() != 0) {
            log.info("金蝶商品查询接口未返回商品数据,erp_code: {} jsonData: {}", jdProductFilter.getProductNumber(), JSON.toJSONString(jdyResult));
            return new JdyResult();
        }
        return jdyResult;
    }

    @Override
    public void productInfoUnitId() {

    }

    //查询金蝶批次
    @Override
    public JdyResult productStockBat(JdStockFilter jdStockFilter) {
        jdStockFilter.setAccess_token(TokenCache.getToken());
        jdStockFilter.setDbId("796392012921816");
        jdStockFilter.setCatId("12961928509993152");
        Map<String, Object> objectMap = BeanUtil.beanToMap(jdStockFilter);
        String body = HttpRequest.get(JdConfig + "/jdyscm/warranty/list").form(objectMap).execute().body();
        if (StrUtil.isBlank(body)) {
            log.warn("金蝶批次接口请求异常！！！！");
            return new JdyResult();
        }
        JdyResult jdyResult = JSON.parseObject(body, JdyResult.class);
        return jdyResult;
    }

    //客户信息查询
    @Override
    public JdyResult CustomerInfo(JdCustomerFilter jdCustomerFilter) {
        ApiRequest request = new ApiRequest(HttpMethod.POST_BODY, JdConfig, "/jdyscm/customer/list");
        Map<String, String> map = new HashMap<>();
        map.put("access_token", TokenCache.getToken());
        map.put("dbId", "796392012921816");
        request.setQuerys(map);
        if (jdCustomerFilter != null) {
            Map<String, String> map1 = new HashMap<>();
            map1.put("filter", JSON.toJSONString(jdCustomerFilter));
            byte[] jsonBytes = JSON.toJSONBytes(map1);
            request.setBodyJson(jsonBytes);
        }
        ApiResult send = ApigwClient.getInstance().send(request);
        if (send == null && send.getHttpCode() != 200) {
            log.warn("未获取到金蝶客户信息!!! jsonData: {} param:{}", JSON.toJSONString(send), JSON.toJSONString(jdCustomerFilter));
            return new JdyResult();
        }
        JdyResult jdyResult = JSON.parseObject(send.getBody(), JdyResult.class);
        return jdyResult;

    }

    //订单导入金蝶
    @Override
    public JdyResult toJdOrderInfo(List<JdOrderSave> orderSaveList) {
        JdyResult jdyResult = JdApi.saveApi(HttpMethod.POST_BODY, "/jdyscm/delivery/add", orderSaveList);
        if (BeanUtil.isEmpty(jdyResult)) {
            log.info("订单导入失败 JsonData: {}", JSON.toJSONString(jdyResult));
        }
        return jdyResult;
    }

    //查询商品批次信息
    @Override
    public OrderDetailSku productInfoSku(String productNumber) {
        JdProductFilter jdProductFilter = new JdProductFilter();
        jdProductFilter.setProductNumber(productNumber);
        JdyResult jdyResult = this.productInfoList(jdProductFilter);
        if (BeanUtil.isEmpty(jdyResult)) {
            return new OrderDetailSku();
        }
        List<JdProductInfoDto> jdProductInfoDtos = JSON.parseArray(JSON.toJSONString(jdyResult.getItems()), JdProductInfoDto.class);
        if (jdProductInfoDtos.size() <= 0 || jdProductInfoDtos.isEmpty()) {
            log.info("金蝶返回商品数据: {},查询条件: {}", JSON.toJSONString(jdyResult), JSON.toJSONString(jdProductFilter));
            return new OrderDetailSku();
        }
        Long unit = jdProductInfoDtos.get(0).getUnit();
        // TODO: 2023/7/29 分摊批号
        JdStockFilter jdStockFilter = new JdStockFilter();
        jdStockFilter.setNumber(productNumber);
        JdyResult jdyResult1 = this.productStockBat(jdStockFilter);
        if (jdyResult1.getCode() != 0) {
            log.warn("筋斗云未查询到商品批次信息: {}", JSON.toJSONString(jdyResult1));
            return new OrderDetailSku();
        }
        List<JdProductStockDto> jdProductStockDtos = JSON.parseArray(JSON.toJSONString(jdyResult1.getItems()), JdProductStockDto.class);
        if (jdProductStockDtos.size() <= 0 || jdProductStockDtos.isEmpty()) {
            log.warn("金蝶返回商品批次数据: {},查询条件: {}", JSON.toJSONString(jdyResult1), JSON.toJSONString(jdStockFilter));
            return new OrderDetailSku();
        }
        JdProductStockDto jdProductStockDto = jdProductStockDtos.stream().filter(m -> productNumber.equals(m.getProductNumber())).min(Comparator.comparing(JdProductStockDto::getProdDate)).orElse(null);
        if (jdProductStockDto == null) {
            log.warn("当前商品,{}-金蝶未查询到批次信息", productNumber);
            return new OrderDetailSku();
        }
        OrderDetailSku orderDetailSku = new OrderDetailSku();
        orderDetailSku.setUnitId(String.valueOf(unit));
        orderDetailSku.setBatch(jdProductStockDto.getBatch());
        orderDetailSku.setProdDate(jdProductStockDto.getProdDate());
        return orderDetailSku;
    }

    @Override
    public JdyResult toJdCustomer(List<JdCustomerPo> customerPos) {
        JdyResult jdyResult = JdApi.saveApi(HttpMethod.POST_BODY, "/jdyscm/customer/add", customerPos);
        if (BeanUtil.isEmpty(jdyResult)) {
            log.info("客户导入失败 JsonData: {}", JSON.toJSONString(jdyResult));
            return new JdyResult<>();
        }
        return jdyResult;
    }

    @Override
    public List<SellerOrderDeliverDetailDto> jdOrderInfoToNumber(List<String> number) {
        List<SellerOrderDeliverDetailDto> deliverDetailDtos = new ArrayList<>();
        for (String s : number) {
            JdOrderInfoFilter jdOrderInfoFilter = new JdOrderInfoFilter();
            jdOrderInfoFilter.setCheckStatus(1);
            jdOrderInfoFilter.setNumber(s);
            JdyResult jdyResult = JdApi.quersyApi(HttpMethod.POST_BODY, "/jdyscm/delivery/list", jdOrderInfoFilter);
            if (jdyResult.getCode() != 0 || BeanUtil.isEmpty(jdyResult)) {
                log.info("金蝶接口未查询到信息, jsonData: {},Filter: {}", JSON.toJSONString(jdyResult), JSON.toJSONString(jdOrderInfoFilter));
                continue;
            }
            List<JdOrderPushInfo> jdOrderPushInfos = JSON.parseArray(JSON.toJSONString(jdyResult.getItems()), JdOrderPushInfo.class);
            for (JdOrderPushInfo jdOrderPushInfo : jdOrderPushInfos) {
                List<JdOrderPushInfo.EntriesDTO> entries = jdOrderPushInfo.getEntries();
                for (JdOrderPushInfo.EntriesDTO entry : entries) {
                    if (entry.getRemark() == null) {
                        continue;
                    }
                    SellerOrderDeliverDetailDto sellerOrderDeliverDetailDto = new SellerOrderDeliverDetailDto();
                    sellerOrderDeliverDetailDto.setOrderNo(jdOrderPushInfo.getNumber());
                    sellerOrderDeliverDetailDto.setOrderDetailId(Long.valueOf(entry.getRemark()));
                    sellerOrderDeliverDetailDto.setErpCode(entry.getProductNumber());
                    sellerOrderDeliverDetailDto.setProductName(entry.getProductName());
                    sellerOrderDeliverDetailDto.setBatchCode(entry.getBatch());
                    sellerOrderDeliverDetailDto.setBatchNum(entry.getQty());
                    sellerOrderDeliverDetailDto.setProductionDate(DateUtils.parserDate(entry.getProdDate(), SHORT_DATE_FORMAT_STR));
                    sellerOrderDeliverDetailDto.setBatchPrice(BigDecimal.valueOf(entry.getPrice()));
                    deliverDetailDtos.add(sellerOrderDeliverDetailDto);
                }
            }
        }
        return deliverDetailDtos;
    }

    //实时库存查询
    @Override
    public JdyResult RealStock(Stcok stcok) {
        stcok.setAccess_token(TokenCache.getToken());
        stcok.setDbId("796392012921816");
        stcok.setLocation("CK001");
        stcok.setIsChecked(1);
        stcok.setShowZero(1);
        ApiRequest apiRequest = new ApiRequest(HttpMethod.GET, "api.kingdee.com", "/jdyscm/inventory/list");
        Map<String, Object> objectMap = BeanUtil.beanToMap(stcok);
        Map<String, String> map = new HashMap<>();
        for (Map.Entry<String, Object> stringObjectEntry : objectMap.entrySet()) {
            if (stringObjectEntry.getValue() == null || stringObjectEntry.getValue() == null) {
                continue;
            }
            map.put(stringObjectEntry.getKey(), stringObjectEntry.getValue().toString());
        }
        apiRequest.setQuerys(map);
        ApiResult send = ApigwClient.getInstance().send(apiRequest);
        JdyResult jdyResult = JSON.parseObject(send.getBody(), JdyResult.class);
        return jdyResult;
    }
}
